import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
import { RedisCacheService } from "src/redis/redis.service";
// import { OrgRepository } from 'src/modules/organization/org.repository'

/**
 * 数据查询权限守卫(每次调用接口都会执行)
 */
@Injectable()
export class DataPermission implements CanActivate {
  constructor(
    private readonly redisCacheService: RedisCacheService
  ) { }

  async canActivate(context: ExecutionContext): Promise<boolean> {

    try {
      // 获取当前参入的查询条件
      const request = context.switchToHttp().getRequest()

      // 从Redis中读取当前用户的权限数组
      // 添加到 body 参数上
      request['body']['premissionIds'] = JSON.parse(await this.redisCacheService.get(request?.user?.loginName + '_userIds') || '[]')
    } catch (error) {
      throw new UnauthorizedException('权限查询错误')
    }

    return true
  }
}